package com.leyou.item.controller;

import com.leyou.common.pojo.PageResult;
import com.leyou.item.pojo.Brand;
import com.leyou.item.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("brand")
public class BrandController {

    @Autowired
    private BrandService brandService;

    //TODO 分页查询(品牌管理)并模糊搜索
    @GetMapping("page")
    public ResponseEntity<PageResult<Brand>> page(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows,
            @RequestParam(value = "key", required = false) String key,//required = false 表示不是必要参数,前端可以穿过来也可以不传
            @RequestParam(value = "sortBy", required = false) String sortBy,
            @RequestParam(value = "desc", defaultValue = "false", required = false) Boolean desc
    ) {
        PageResult<Brand> pageResult = this.brandService.page(page, rows, sortBy, desc, key);
        if (pageResult != null && null != pageResult.getItems() && 0 != pageResult.getItems().size()) {
            return ResponseEntity.ok(pageResult);
        }
        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }

    //TODO 添加品牌的保存
    //传来的字符串是逗号分割的,SpringMvc消息转换器会处理有特征的字符串,所以传来的字符串被转换成集合数组了,所以直接用集合接收
    @PostMapping
    public ResponseEntity<Void> addBrand(Brand brand, @RequestParam("cids") List<Long> cids) {
        this.brandService.addBrand(brand, cids);
        return ResponseEntity.status(201).build();//返回201表示注册完成
    }

    //TODO 修改品牌
    @PutMapping
    public ResponseEntity<Void> updateBrand(Brand brand, @RequestParam("cids") List<Long> cids) {
        this.brandService.updateBrand(brand, cids);
        return ResponseEntity.status(201).build();//返回201表示注册完成
    }

    @GetMapping("cid/{cid}")
    public ResponseEntity<List<Brand>> queryBrandByCategory(@PathVariable("cid") Long cid) {
        List<Brand> list = this.brandService.queryBrandByCategory(cid);
        if (list != null) {
            return ResponseEntity.ok(list);
        }
        return ResponseEntity.status(204).build();
    }

    @GetMapping("brandId")
    ResponseEntity<String> queryBrandByIds(@RequestParam("bid") Long bid) {
        Brand brand = this.brandService.queryBrandById(bid);
        if (brand != null) {
            return ResponseEntity.ok(brand.getName());
        }
        return ResponseEntity.status(204).build();
    }

    @GetMapping
    ResponseEntity<List<Brand>> queryBrandByIds(@RequestParam(value = "bids", required = false) List<Long> bids) {
        List<Brand> brands = this.brandService.queryBrandByIds(bids);
        if (brands != null && 0 != brands.size()) {
            return ResponseEntity.ok(brands);
        }
        return ResponseEntity.status(204).build();
    }
}
